{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# pands\n",
    "Pandas是基于NumPy构建的专门为处理表格和混杂数据设计的Python库，核心设计理念包括:<br>\n",
    "-标签化数据结构:提仗带标签的轴<br>\n",
    "-灵活处理缺失数据:内置NaN处理机制<br>\n",
    "-智能数据对齐:自动按标签对齐数据<br>\n",
    "-强大IO工具:支持从CSv、Excel、SQL等20+数据源读写<br>\n",
    "-时间序列处理:原生支持日期时间处理和频率转换<br>\n"
   ],
   "id": "d58b196c4cde0700"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "f4410a6465b0b298"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "\n",
    "| 特性          | Series                          | DataFrame                          |\n",
    "|---------------|---------------------------------|------------------------------------|\n",
    "| **维度**      | 一维                            | 二维                                |\n",
    "| **索引**      | 单索引（默认0-based或自定义）   | 行索引 + 列名（双重标签）           |\n",
    "| **数据存储**  | 同质化数据类型（如全整数）      | 各列可不同数据类型（如混合整数/字符串）|\n",
    "| **类比**      | 类似Excel中的单列               | 类似整张Excel工作表                 |\n",
    "| **创建方式**  | `pd.Series([1, 2, 3])`         | `pd.DataFrame({'col': [1, 2, 3]})` |"
   ],
   "id": "eb430735a17b2d73"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## series\n",
   "id": "d302f2b0a4511c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-17T18:39:29.837956Z",
     "start_time": "2025-07-17T18:39:29.817139Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#1.创建series\n",
    "import pandas as pd\n",
    "s = pd.Series([1, 2, 3])\n",
    "print(s) #第一列索引 默认从0开始 第二列数据\n",
    "# 0    1\n",
    "# 1    2\n",
    "# 2    3\n",
    "# dtype: in\n",
    "#2.自定义index\n",
    "s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])\n",
    "print(s)\n",
    "# a    1\n",
    "# b    2\n",
    "# c    3\n",
    "# dtype: int64\n",
    "#获取值\n",
    "print(s['a']) # 1\n",
    "\n",
    "#定义名称\n",
    "s = pd.Series([1, 2, 3], index=['a', 'b', 'c'], name='num')\n",
    "print(s)"
   ],
   "id": "c0669a9e550b2bd6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    1\n",
      "1    2\n",
      "2    3\n",
      "dtype: int64\n",
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "dtype: int64\n",
      "1\n",
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "Name: num, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-17T18:43:30.319295Z",
     "start_time": "2025-07-17T18:43:30.313293Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 通过字典创建series\n",
    "s = pd.Series({'a': 1, 'b': 2, 'c': 3})\n",
    "print(s)\n",
    "\n",
    "#取一部分作为新series\n",
    "s1 = pd.Series(s, index=['a', 'b'])\n",
    "print(s1)\n"
   ],
   "id": "7cf5549f6ab81b5b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "dtype: int64\n",
      "a    1\n",
      "b    2\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2.seires属性",
   "id": "5d996cbafff7ed1a"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "| **属性/方法** | **说明**              | **属性/方法** | **说明**                              |\n",
    "|---------------|---------------------|---------------|---------------------------------------|\n",
    "| `index`       | Series的索引对象（标签集合）   | `loc[]`       | 显式索引，按**标签**访问或切片        |\n",
    "| `values`      | Series的值（返回NumPy数组） | `iloc[]`      | 隐式索引，按**位置**访问或切片        |\n",
    "| `dtype`       | Series元素的数据类型       | `at[]`        | 使用**标签**快速访问**单个元素**      |\n",
    "| `shape`       | Series的形状（如 `(n,)`） | `iat[]`       | 使用**位置**快速访问**单个元素**      |\n",
    "| `ndim`        | Series的维度（固定为1）     | `size`        | Series的元素个数                      |\n",
    "| `name`        | Series的 名称（可通过赋值修改） |               |                                       |"
   ],
   "id": "6baf6eb37eb0824c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:30:57.307394Z",
     "start_time": "2025-08-20T09:30:57.287667Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([1, 2, 3], index=['a', 'b', 'c'], name='num')\n",
    "# index:Series的索引对象\n",
    "print(s.index)\n",
    "print(s['a'])\n",
    "print(s.loc['b'])\n",
    "# values:Series的值\n",
    "print(s.values)\n",
    "# dtype或dtypes\"Series的元素类型\n",
    "print(s.dtype)\n",
    "# shape:Series的形状\n",
    "print(s.shape)\n",
    "# ndim:Series的维度\n",
    "print(s.ndim)\n",
    "# size:Series的元素个数\n",
    "print(s.size)\n",
    "# name:Series的名称\n",
    "print(s.name)"
   ],
   "id": "f46147a9c6fa6a25",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['a', 'b', 'c'], dtype='object')\n",
      "1\n",
      "2\n",
      "[1 2 3]\n",
      "int64\n",
      "(3,)\n",
      "1\n",
      "3\n",
      "num\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-20T11:25:09.427450Z",
     "start_time": "2025-07-20T11:25:09.419070Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "s = pd.Series([1, 2, 3], index=['a', 'b', 'c'], name='num')\n",
    "\n",
    "print(s['a']) #需要使用显示索引\n",
    "# loc[]  显式索引，按标签索引或切片 支持切片\n",
    "print(s.loc['a'])\n",
    "print(s.loc['a':'b']) #切片\n",
    "# iloc[]  隐式索引，按位置索引或切片 支持切片\n",
    "print(s.iloc[0])\n",
    "print(s.iloc[0:2]) #切片\n",
    "# at[]  使用标签访问单个元素 不支持切片\n",
    "print(s.at['a'])\n",
    "# iat[]  使用位置访问单个元素不支持切片\n",
    "print(s.iat[0])\n",
    "\n",
    "#布尔过滤\n",
    "s = pd.Series([3, 2, 1], index=['a', 'b', 'c'], name='num')\n",
    "print(\"--------------\")\n",
    "print(s[s > 1]) #里面的值，而非索引\n",
    "print(s[s.values > 1])\n",
    "print(s[s.index == 'a'])"
   ],
   "id": "63baa3d614c51809",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "a    1\n",
      "b    2\n",
      "Name: num, dtype: int64\n",
      "1\n",
      "a    1\n",
      "b    2\n",
      "Name: num, dtype: int64\n",
      "1\n",
      "1\n",
      "--------------\n",
      "a    3\n",
      "b    2\n",
      "Name: num, dtype: int64\n",
      "a    3\n",
      "b    2\n",
      "Name: num, dtype: int64\n",
      "a    3\n",
      "Name: num, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-20T11:27:36.249733Z",
     "start_time": "2025-07-20T11:27:36.243184Z"
    }
   },
   "cell_type": "code",
   "source": [
    "+-----------+-----------------------------------------+\n",
    "|  方法      | 说明                                    |\n",
    "+-----------+-----------------------------------------+\n",
    "| head()    | 查看前n行数据，默认5行                   |\n",
    "| tail()    | 查看后n行数据，默认5行                   |\n",
    "| isin()    | 判断元素是否包含在参数集合中             |\n",
    "| isna()    | 判断是否为缺失值（如NaN或None）          |\n",
    "| max()     | 最大值                                  |\n",
    "| min()     | 最小值                                  |\n",
    "| mean()    | 平均值                                  |\n",
    "| median()  | 中位数                                  |\n",
    "| mode()    | 众数（可返回多个）                       |\n",
    "| sum()     | 求和，自动忽略缺失值                     |\n",
    "| var()     | 方差                                    |\n",
    "| std()     | 标准差                                  |\n",
    "| quantile(q)| 分位数，q取0~1之间                     |\n",
    "| describe()| 常见统计信息(count,mean,std,min,25%,    |\n",
    "|           | 50%,75%,max)                           |\n",
    "+-----------+-----------------------------------------+\n",
    "\n",
    "#head\n",
    "s = pd.Series([1, 2, 3], index=['a', 'b', 'c'], name='num')\n",
    "print(s.head()) #默认显示前5行\n",
    "print(s.head(2)) #显示前2行\n",
    "print(s.tail()) #默认显示最后5行\n",
    "print(s.tail(2)) #显示最后2行\n",
    "\n",
    "\n",
    "\n"
   ],
   "id": "3f5ff6a0fe238e6c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "Name: num, dtype: int64\n",
      "a    1\n",
      "b    2\n",
      "Name: num, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "+------------------+-----------------------------------+\n",
    "| 方法             | 说明                              |\n",
    "+------------------+-----------------------------------+\n",
    "| value_counts()   | 每个唯一值的出现次数              |\n",
    "| sort_values()    | 按值排序                          |\n",
    "| count()          | 非缺失值数量                      |\n",
    "| replace()        | 替换值,不改变原数组                |\n",
    "| nunique()        | 唯一值个数（去重）                |\n",
    "| keys()           | 返回Series的索引对象              |\n",
    "| unique()         | 获取去重后的值数组                |\n",
    "| drop_duplicates()| 去除重复项                        |\n",
    "| sample()         | 随机抽样                          |\n",
    "| sort_index()     | 按索引排序                        |\n",
    "+------------------+-----------------------------------+"
   ],
   "id": "6c3c572bfadea300"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:34:21.021744Z",
     "start_time": "2025-08-20T09:34:21.002932Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#创建 series\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "s = pd.Series([1, 2, 3,None,np.nan], index=['a', 'b', 'c', 'd', 'e'], name='num')\n",
    "print(s)\n",
    "print(s.replace(2,4))\n",
    "#head 前取\n",
    "print(s.head())\n",
    "print(s.head(3))\n",
    "#tail 后取\n",
    "print(s.tail())\n",
    "print(s.tail(2))\n",
    "\n",
    "#describe 获取所有描述信息 忽略None\n",
    "print(s.describe())\n",
    "print(type(s.describe()))\n",
    "\n",
    "#count 忽略缺失值\n",
    "print(s.count()) #3\n",
    "\n",
    "#value_counts\n",
    "print(s.value_counts()) #\n"
   ],
   "id": "990091a07f1068ba",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    NaN\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    4.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    NaN\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    NaN\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    NaN\n",
      "Name: num, dtype: float64\n",
      "d   NaN\n",
      "e   NaN\n",
      "Name: num, dtype: float64\n",
      "count    3.0\n",
      "mean     2.0\n",
      "std      1.0\n",
      "min      1.0\n",
      "25%      1.5\n",
      "50%      2.0\n",
      "75%      2.5\n",
      "max      3.0\n",
      "Name: num, dtype: float64\n",
      "<class 'pandas.core.series.Series'>\n",
      "3\n",
      "num\n",
      "1.0    1\n",
      "2.0    1\n",
      "3.0    1\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-20T12:40:09.702873Z",
     "start_time": "2025-07-20T12:40:09.694876Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#keys 方法，获取索引\n",
    "print(s.keys())\n",
    "print(type(s.keys()))\n",
    "#index 属性，获取索引\n",
    "print(s.index)\n",
    "print(type(s.index))\n",
    "#isna() 判断是否缺失值\n",
    "s.isna()\n",
    "# print(s.isna())"
   ],
   "id": "a96ba35f0da48a66",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')\n",
      "<class 'pandas.core.indexes.base.Index'>\n",
      "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')\n",
      "<class 'pandas.core.indexes.base.Index'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "a    False\n",
       "b    False\n",
       "c    False\n",
       "d     True\n",
       "e     True\n",
       "Name: num, dtype: bool"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-20T13:21:17.978407Z",
     "start_time": "2025-07-20T13:21:17.955480Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "s = pd.Series([1, 2, 3,None,np.nan], index=['a', 'b', 'c', 'd', 'e'], name='num')\n",
    "#isin() 判断元素是否包含在参数集合中(注意是判断series的元素在不在传入的数组中)\n",
    "print(s.isin([1, 2]))\n",
    "\n",
    "print(s.mean) #平均值\n",
    "print(s.median()) #中位数\n",
    "print(s.mode()) #众数\n",
    "print(s.sum()) #求和\n",
    "print(\"var:\" , s.var()) #方差\n",
    "print(\"std:\",s.std()) #标准差\n",
    "print(\"quantile1:\",s.quantile(0.5)) #分位数\n",
    "print(\"quantile2:\",s.quantile([0.25, 0.5, 0.75])) #分位数\n",
    "#去重\n",
    "print(s.unique()) #返回list[ 1.  2.  3. nan]\n",
    "print(s.nunique()) # 3\n",
    "print(s.drop_duplicates()) #返回series [ 1.  2.  3. nan]"
   ],
   "id": "8bd7fd4313df609c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a     True\n",
      "b     True\n",
      "c    False\n",
      "d    False\n",
      "e    False\n",
      "Name: num, dtype: bool\n",
      "<bound method Series.mean of a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    NaN\n",
      "Name: num, dtype: float64>\n",
      "2.0\n",
      "0    1.0\n",
      "1    2.0\n",
      "2    3.0\n",
      "Name: num, dtype: float64\n",
      "6.0\n",
      "var: 1.0\n",
      "std: 1.0\n",
      "quantile1: 2.0\n",
      "quantile2: 0.25    1.5\n",
      "0.50    2.0\n",
      "0.75    2.5\n",
      "Name: num, dtype: float64\n",
      "[ 1.  2.  3. nan]\n",
      "3\n",
      "a    1.0\n",
      "b    2.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "Name: num, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-20T13:22:19.750777Z",
     "start_time": "2025-07-20T13:22:19.740085Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#随机抽样 n为数量\n",
    "print(s.sample(n=2))\n",
    "#排序\n",
    "print(s.sort_values())\n",
    "print(s.sort_index())"
   ],
   "id": "a117010e62232f7a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "e    NaN\n",
      "b    2.0\n",
      "Name: num, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 案例",
   "id": "6bd94ecb87201dac"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-21T15:08:01.239038Z",
     "start_time": "2025-07-21T15:07:58.732821Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#1.创建一个包含10名学生数学成绩的Series，成绩范围在50-100之间。计算平均分、最高分、最低分，并找出高于平均分的学生人数。\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "np.random.seed(42)\n",
    "s = pd.Series(np.random.randint(50, 101, 10), index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])\n",
    "print(s)\n",
    "print(\"平均分:\",s.mean())\n",
    "print(\"最高分:\",s.max())\n",
    "print(\"最低分:\",s.min())\n",
    "print(\"高于平均分学生人数:\",len(s[s > s.mean()]))\n"
   ],
   "id": "3ea6bb860f5e2edf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    88\n",
      "b    78\n",
      "c    64\n",
      "d    92\n",
      "e    57\n",
      "f    70\n",
      "g    88\n",
      "h    68\n",
      "i    72\n",
      "j    60\n",
      "dtype: int32\n",
      "平均分: 73.7\n",
      "最高分: 92\n",
      "最低分: 57\n",
      "高于平均分学生人数: 4\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:43:11.284796Z",
     "start_time": "2025-08-20T09:43:11.272101Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#2.给定某城市一周每天的最高温度Series，完成以下任务:\n",
    "# 找出温度超过30度的天数  \n",
    "# 计算平均温度\n",
    "# 将温度从高到低排序\n",
    "# 找出温度变化最大的两天\n",
    "\n",
    "temp = pd.Series([25, 28, 30, 32, 34, 36, 38], index=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])\n",
    "# print(len(temp[temp>30]))\n",
    "# print(temp.mean)\n",
    "# print(temp.sort_values(ascending=False))\n",
    "temp.diff()\n",
    "print(temp.diff())\n",
    "print(temp.diff().abs().sort_values(ascending=False)[0:2].index.tolist())\n",
    "print(temp.diff().abs().sort_values(ascending=False)[0:2].values.tolist())\n"
   ],
   "id": "8962895b8c4bcbcd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mon    NaN\n",
      "Tue    3.0\n",
      "Wed    2.0\n",
      "Thu    2.0\n",
      "Fri    2.0\n",
      "Sat    2.0\n",
      "Sun    2.0\n",
      "dtype: float64\n",
      "['Tue', 'Wed']\n",
      "[3.0, 2.0]\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-20T14:49:43.128956Z",
     "start_time": "2025-07-20T14:49:43.119392Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 3.给定某股票连续10个交易日的收盘价Series\n",
    "# 计算每日收益率（当日收盘价/前日收盘价)\n",
    "# 找出收益率最高和最低的日期\n",
    "# 计算波动率（收益率的标准差)\n",
    "\n",
    "close_price = pd.Series([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], index=pd.date_range('2023-1-1', periods=10))\n",
    "# print(close_price)\n",
    "print(close_price.pct_change()) #每日收益率\n",
    "\n",
    "# print(close_price.sort_values().iloc[0])\n",
    "# print(close_price.sort_values(ascending=False).iloc[0])\n",
    "print(close_price.idxmax())#最高日期\n",
    "print(close_price.idxmin())#最低日期\n",
    "\n",
    "print(close_price.pct_change().std()) #波动率\n"
   ],
   "id": "c6e48189e811a38c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2023-01-01         NaN\n",
      "2023-01-02    0.100000\n",
      "2023-01-03    0.090909\n",
      "2023-01-04    0.083333\n",
      "2023-01-05    0.076923\n",
      "2023-01-06    0.071429\n",
      "2023-01-07    0.066667\n",
      "2023-01-08    0.062500\n",
      "2023-01-09    0.058824\n",
      "2023-01-10    0.055556\n",
      "Freq: D, dtype: float64\n",
      "2023-01-10 00:00:00\n",
      "2023-01-01 00:00:00\n",
      "0.015086142175536424\n"
     ]
    }
   ],
   "execution_count": 51
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-20T09:43:53.605724Z",
     "start_time": "2025-08-20T09:43:53.586945Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 4.某产品过去12个月的销售量Series:\n",
    "# 计算季度平均销量（每3个月为一个季度)\n",
    "# 找出销量最高的月份\n",
    "# 计算月环比增长率\n",
    "# 找出连续增长超过2个月的月份\n",
    "import pandas as pd\n",
    "\n",
    "sales = pd.Series([100, 120, 130, 140, 100, 160, 170, 180, 100, 200, 210, 220], index=pd.date_range('2023-1-1', periods=12, freq='MS'))\n",
    "print(sales.resample('QS'))\n",
    "print(\"--# 计算季度平均销量（每3个月为一个季度)--\")\n",
    "print(sales.resample('QS').mean()) #季度平均销量\n",
    "print(type(sales.resample('QS').mean())) #<class 'pandas.core.series.Series'>\n",
    "print(sales.idxmax()) #销量最高的月份\n",
    "# print(sales.diff()[1:]/sales[1:]) #月环比增长率\n",
    "print(sales.pct_change())#月环比增长率\n",
    "change = sales.pct_change()\n",
    "a = change>0 #結果是日期為key，值為bool的serires,只是把結果轉成bool\n",
    "print(change[a])#找出增长率为正数的月份\n",
    "print(\"a:--------------\")\n",
    "print( a)\n",
    "#滑动窗口 rolling\n",
    "print(\"res:\")\n",
    "# a[a.rolling(3).sum()==3].keys().tolist()\n",
    "print(a[a.rolling(3).sum()==3].keys().tolist()) #rolling窗口"
   ],
   "id": "fa1621575880ef4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DatetimeIndexResampler [freq=<QuarterBegin: startingMonth=1>, axis=0, closed=left, label=left, convention=start, origin=start_day]\n",
      "--# 计算季度平均销量（每3个月为一个季度)--\n",
      "2023-01-01    116.666667\n",
      "2023-04-01    133.333333\n",
      "2023-07-01    150.000000\n",
      "2023-10-01    210.000000\n",
      "Freq: QS-JAN, dtype: float64\n",
      "<class 'pandas.core.series.Series'>\n",
      "2023-12-01 00:00:00\n",
      "2023-01-01         NaN\n",
      "2023-02-01    0.200000\n",
      "2023-03-01    0.083333\n",
      "2023-04-01    0.076923\n",
      "2023-05-01   -0.285714\n",
      "2023-06-01    0.600000\n",
      "2023-07-01    0.062500\n",
      "2023-08-01    0.058824\n",
      "2023-09-01   -0.444444\n",
      "2023-10-01    1.000000\n",
      "2023-11-01    0.050000\n",
      "2023-12-01    0.047619\n",
      "Freq: MS, dtype: float64\n",
      "2023-02-01    0.200000\n",
      "2023-03-01    0.083333\n",
      "2023-04-01    0.076923\n",
      "2023-06-01    0.600000\n",
      "2023-07-01    0.062500\n",
      "2023-08-01    0.058824\n",
      "2023-10-01    1.000000\n",
      "2023-11-01    0.050000\n",
      "2023-12-01    0.047619\n",
      "dtype: float64\n",
      "a:--------------\n",
      "2023-01-01    False\n",
      "2023-02-01     True\n",
      "2023-03-01     True\n",
      "2023-04-01     True\n",
      "2023-05-01    False\n",
      "2023-06-01     True\n",
      "2023-07-01     True\n",
      "2023-08-01     True\n",
      "2023-09-01    False\n",
      "2023-10-01     True\n",
      "2023-11-01     True\n",
      "2023-12-01     True\n",
      "Freq: MS, dtype: bool\n",
      "res:\n",
      "[Timestamp('2023-04-01 00:00:00'), Timestamp('2023-08-01 00:00:00'), Timestamp('2023-12-01 00:00:00')]\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-07-21T15:50:15.253299Z",
     "start_time": "2025-07-21T15:50:15.237858Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 某商店每小时销售额Series:(\n",
    "# 按天重采样计算每日总销售额)\n",
    "# 计算每天营业时间(8:00-22:00）和非营业时间的销售额比例\n",
    "# 找出销售额最高的3个小时\n",
    "np.random.seed(42)\n",
    "sales = pd.Series(np.random.randint(100, 300, 48), index=pd.date_range('2023-1-1', periods=48, freq='h'))\n",
    "print(sales)\n",
    "print(\"-----------按天重采样计算每日总销售额-----------\")\n",
    "print(sales.resample('D'))\n",
    "print(sales.resample('D').sum()) #按天重采样计算每日总销售额\n",
    "\n",
    "print(\"-----------计算每天营业时间(8:00-22:00）和非营业时间的销售额比例-----------\")\n",
    "print(sales.between_time('08:00', '22:00').sum()/sales.sum())\n",
    "# sales.index.hour>=8 & sales.index.hour<=22\n",
    "print(sales[(sales.index.hour>=8) & (sales.index.hour<=22)].sum()/sales.sum())\n",
    "# sales.drop(sales[(sales.index.hour<8) | (sales.index.hour>22)].index)\n",
    "#drop删除的是索引，注意\n",
    "# print(sales[(sales.index.hour>=8) & (sales.index.hour<=22)]) #找出营业时间\n",
    "# 找出非营业时间\n",
    "print(\"-----------找出非营业时间销售额-----------\")\n",
    "print(\"~取反：\")\n",
    "print(sales[~(sales.index.hour>=8) & (sales.index.hour<=22)]) #找出营业时间\n",
    "\n",
    "print(\"drop删除营业时间：\")\n",
    "# print(sales[(sales.index.hour>=8) & (sales.index.hour<=22)].index) #找出营业时间索引\n",
    "# print(sales.drop(sales[(sales.index.hour>=8) & (sales.index.hour<=22)].index))\n",
    "print(sales.drop(sales[(sales.index.hour>=8) & (sales.index.hour<=22)].index).sum()/sales.sum())\n",
    "# print(sales.drop(sales[(sales.index.hour>=8) & (sales.index.hour<=22)].index)/sales.sum())\n",
    "\n",
    "print(\"-----------找出销售额最高的3个小时-----------\")\n",
    "print(sales.nlargest(3).index.tolist())\n",
    "print(sales.idxmax()) #值最高的索引\n",
    "print(sales.argmax())#最高的值\n"
   ],
   "id": "befddf1568f1a46a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2023-01-01 00:00:00    202\n",
      "2023-01-01 01:00:00    279\n",
      "2023-01-01 02:00:00    192\n",
      "2023-01-01 03:00:00    114\n",
      "2023-01-01 04:00:00    206\n",
      "2023-01-01 05:00:00    171\n",
      "2023-01-01 06:00:00    288\n",
      "2023-01-01 07:00:00    120\n",
      "2023-01-01 08:00:00    202\n",
      "2023-01-01 09:00:00    221\n",
      "2023-01-01 10:00:00    174\n",
      "2023-01-01 11:00:00    187\n",
      "2023-01-01 12:00:00    216\n",
      "2023-01-01 13:00:00    199\n",
      "2023-01-01 14:00:00    203\n",
      "2023-01-01 15:00:00    251\n",
      "2023-01-01 16:00:00    230\n",
      "2023-01-01 17:00:00    249\n",
      "2023-01-01 18:00:00    152\n",
      "2023-01-01 19:00:00    101\n",
      "2023-01-01 20:00:00    187\n",
      "2023-01-01 21:00:00    257\n",
      "2023-01-01 22:00:00    137\n",
      "2023-01-01 23:00:00    229\n",
      "2023-01-02 00:00:00    291\n",
      "2023-01-02 01:00:00    287\n",
      "2023-01-02 02:00:00    120\n",
      "2023-01-02 03:00:00    260\n",
      "2023-01-02 04:00:00    157\n",
      "2023-01-02 05:00:00    121\n",
      "2023-01-02 06:00:00    188\n",
      "2023-01-02 07:00:00    148\n",
      "2023-01-02 08:00:00    158\n",
      "2023-01-02 09:00:00    269\n",
      "2023-01-02 10:00:00    287\n",
      "2023-01-02 11:00:00    114\n",
      "2023-01-02 12:00:00    289\n",
      "2023-01-02 13:00:00    289\n",
      "2023-01-02 14:00:00    274\n",
      "2023-01-02 15:00:00    289\n",
      "2023-01-02 16:00:00    150\n",
      "2023-01-02 17:00:00    207\n",
      "2023-01-02 18:00:00    154\n",
      "2023-01-02 19:00:00    163\n",
      "2023-01-02 20:00:00    230\n",
      "2023-01-02 21:00:00    150\n",
      "2023-01-02 22:00:00    234\n",
      "2023-01-02 23:00:00    120\n",
      "Freq: h, dtype: int32\n",
      "-----------按天重采样计算每日总销售额-----------\n",
      "DatetimeIndexResampler [freq=<Day>, axis=0, closed=left, label=left, convention=start, origin=start_day]\n",
      "2023-01-01    4767\n",
      "2023-01-02    4949\n",
      "Freq: D, dtype: int32\n",
      "-----------计算每天营业时间(8:00-22:00）和非营业时间的销售额比例-----------\n",
      "0.6404899135446686\n",
      "0.6404899135446686\n",
      "-----------找出非营业时间销售额-----------\n",
      "~取反：\n",
      "2023-01-01 00:00:00    202\n",
      "2023-01-01 01:00:00    279\n",
      "2023-01-01 02:00:00    192\n",
      "2023-01-01 03:00:00    114\n",
      "2023-01-01 04:00:00    206\n",
      "2023-01-01 05:00:00    171\n",
      "2023-01-01 06:00:00    288\n",
      "2023-01-01 07:00:00    120\n",
      "2023-01-02 00:00:00    291\n",
      "2023-01-02 01:00:00    287\n",
      "2023-01-02 02:00:00    120\n",
      "2023-01-02 03:00:00    260\n",
      "2023-01-02 04:00:00    157\n",
      "2023-01-02 05:00:00    121\n",
      "2023-01-02 06:00:00    188\n",
      "2023-01-02 07:00:00    148\n",
      "dtype: int32\n",
      "drop删除营业时间：\n",
      "0.3595100864553314\n",
      "-----------找出销售额最高的3个小时-----------\n",
      "[Timestamp('2023-01-02 00:00:00'), Timestamp('2023-01-02 12:00:00'), Timestamp('2023-01-02 13:00:00')]\n",
      "2023-01-02 00:00:00\n",
      "24\n"
     ]
    }
   ],
   "execution_count": 31
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "9b840ec74c95b330"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
